/*
	If all uploads succeed: {"success":true}
	If an upload fails: {"success":false,"error":"Reason for error!"}
*/
var keel={};

keel.UploadPanel = function(cfg){
	this.width = 510;
	this.height = 200;
	this.removeUpload =true;
	Ext.apply(this,cfg);	
	var me =this;
	var updateStats=function(store){
		var tme =me;
		var count =0;
		for(var i=0;i<this.getCount();i++){
			var rec =this.getAt(i);
			if(rec.get('state')==-4){
			    count++;
			}
		}
		tme.swfupload.setStats({successful_uploads:count});
	}
	this.gp = new Ext.grid.GridPanel({
		border :false,
		viewConfig:{
			forceFit:true
		},
		store: new Ext.data.Store({
			fields:['id','name','type','size','state','percent','url']
			,listeners:{
			   remove:updateStats
			}
		}),
	    columns: [
	    	new Ext.grid.RowNumberer(),
	        {header: '文件名', width: 100, sortable: false,dataIndex: 'name', menuDisabled:true},
	        {header: '类型', width: 70, sortable: false,dataIndex: 'type', menuDisabled:true},
	        {header: '大小', width: 100, sortable: false,dataIndex: 'size', menuDisabled:true,renderer:this.formatFileSize},
	        {header: '进度', width: 150, sortable: false,dataIndex: 'percent', menuDisabled:true,renderer:this.formatProgressBar,scope:this},
	        {header: '状态', width: 70, sortable: false,dataIndex: 'state', menuDisabled:true,renderer:this.formatFileState,scope:this},
	        {header: '操作 ',width:40,dataIndex:'id', menuDisabled:true,renderer:this.formatDelBtn}       
	    ]			
	});
	this.deletePath=this.deletePath||'fileFileName';
	this.setting = {
		upload_url : this.uploadUrl, 
		flash_url : this.flashUrl,
		file_size_limit : this.fileSize || "50 MB",//上传文件体积上限，单位MB
		file_post_name : this.filePostName,
		file_types : this.fileTypes||"*.*",  //允许上传的文件类型 
        file_types_description : this.file_types_description||"所有文件",  //文件类型描述
        file_upload_limit : this.fileCount||"0",  //限定用户一次性最多上传多少个文件，在上传过程中，该数字会累加，如果设置为“0”，则表示没有限制 
        //file_queue_limit : "10",//上传队列数量限制，该项通常不需设置，会根据file_upload_limit自动赋值              
		post_params : this.postParams||{savePath:'upload\\'},
		use_query_string : true,
		debug : false,
		button_cursor : SWFUpload.CURSOR.HAND,
		button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
		custom_settings : {//自定义参数
			scope_handler : this
		},
		file_queued_handler : this.onFileQueued,
		swfupload_loaded_handler : function(){},// 当Flash控件成功加载后触发的事件处理函数
		file_dialog_start_handler : function(){},// 当文件选取对话框弹出前出发的事件处理函数
		file_dialog_complete_handler : this.onDiaogComplete,//当文件选取对话框关闭后触发的事件处理
		upload_start_handler : this.onUploadStart,// 开始上传文件前触发的事件处理函数
		upload_success_handler : this.onUploadSuccess,// 文件上传成功后触发的事件处理函数 
		swfupload_loaded_handler : function(){},// 当Flash控件成功加载后触发的事件处理函数  
		upload_progress_handler : this.uploadProgress,
		upload_complete_handler : this.onUploadComplete,
		upload_error_handler : this.onUploadError,
		file_queue_error_handler : this.onFileError
	};
	keel.UploadPanel.superclass.constructor.call(this,{				
		tbar : [
			{text:'添加文件',iconCls:'upload-add',ref:'../addBtn'},'-',
			{text:'上传',ref:'../uploadBtn',iconCls:'upload-up',handler:this.startUpload,scope:this},'-',
			{text:'停止上传',ref:'../stopBtn',iconCls:'upload-stop',handler:this.stopUpload,scope:this,disabled:true},'-',
			{text:'删除所有',ref:'../deleteBtn',iconCls:'upload-delete',handler:this.deleteAll,scope:this},'-'
		],
		layout : 'fit',
		items : [this.gp],
		listeners : {
			'afterrender':function(){
				var em = this.getTopToolbar().get(0).el.child('em');
				var placeHolderId = Ext.id();
				em.setStyle({
					position : 'relative',
					display : 'block'
				});
				em.createChild({
					tag : 'div',
					id : placeHolderId
				});
				this.swfupload = new SWFUpload(Ext.apply(this.setting,{
					button_width : em.getWidth(),
					button_height : em.getHeight(),
					button_placeholder_id :placeHolderId
				}));
				this.swfupload.uploadStopped = false;
				Ext.get(this.swfupload.movieName).setStyle({
					position : 'absolute',
					top : 0,
					left : 0
				});				
			},
			'destory':function(){
				this.swfupload.destroy();
			},
			scope : this,
			delay : 100
		}
	});
}
Ext.extend(keel.UploadPanel,Ext.Panel,{
	toggleBtn :function(bl){
		this.addBtn.setDisabled(bl);
		this.uploadBtn.setDisabled(bl);
		this.deleteBtn.setDisabled(bl);
		this.stopBtn.setDisabled(!bl);
		this.gp.getColumnModel().setHidden(6,bl);
	},
 	onUploadStart : function(file) {  
	   var post_params = this.settings.post_params;
	   this.setPostParams(post_params);  
	},
	startUpload : function() {
		if (this.swfupload) {
			if (this.swfupload.getStats().files_queued > 0) {
				this.swfupload.uploadStopped = false;
				this.toggleBtn(true);
				this.swfupload.startUpload();
			}
		}
	},
	formatFileSize : function(_v, celmeta, record) {
		return Ext.util.Format.fileSize(_v);
	},
	formatFileState : function(n){//文件状态
		switch(n){
			case -1 : return '未上传';
			break;
			case -2 : return '正在上传';
			break;
			case -3 : return '<div style="color:red;">上传失败</div>';
			break;
			case -4 : return '上传成功';
			break;
			case -5 : return '取消上传';
			break;
			default: return n;
		}
	},
	formatProgressBar : function(v){
		var progressBarTmp = this.getTplStr(v);
		return progressBarTmp;
	},
	getTplStr : function(v){
		var bgColor = "orange";
	    var borderColor = "#008000";
		return String.format(
			'<div>'+
				'<div style="border:1px solid {0};height:10px;width:{1}px;margin:4px 0px 1px 0px;float:left;">'+		
					'<div style="float:left;background:{2};width:{3}%;height:10px;"><div></div></div>'+
				'</div>'+
			'<div style="text-align:center;float:right;width:40px;margin:3px 0px 1px 0px;height:10px;font-size:12px;">{3}%</div>'+			
		'</div>', borderColor,(90),bgColor, v);
	},
	onUploadComplete : function(file) {
		var me = this.customSettings.scope_handler;
		if(file.filestatus==-4){
			var ds = me.gp.store;
			for(var i=0;i<ds.getCount();i++){
				var record =ds.getAt(i);
				if(record.get('id')==file.id){
					record.set('percent', 100);
					if(record.get('state')!=-3){
						record.set('state', file.filestatus);
					}
					record.commit();
				}
			}
		}
		
		if (this.getStats().files_queued > 0 && this.uploadStopped == false) {
			this.startUpload();
		}else{			
			me.toggleBtn(false);
			me.linkBtnEvent();
		}		
	},
	onFileQueued : function(file) {
		var me = this.customSettings.scope_handler;
		var store =me.gp.store;
		for(var i=0;i<store.getCount();i++){
			var rec =store.getAt(i);
			if(rec.get('name')==file.name){
			    MsgTip.msg({
			     msg:rec.get('name')+"文件已经存在"
			     ,cmp:me
			     ,pos:'center'
				});
				me.gp.getSelectionModel().selectRow(i);
				return;
			}
		}
		var rec = new Ext.data.Record({
			id : file.id,
			name : file.name,
			size : file.size,
			type : file.type,
			state : file.filestatus,
			percent : 0,
			url:''
		})
		
		me.gp.getStore().add(rec);
	},
	onUploadSuccess : function(file, serverData) {
		var me = this.customSettings.scope_handler;
		var ds = me.gp.store;
		var data =Ext.util.JSON.decode(serverData);
		if (data.success) {			
			for(var i=0;i<ds.getCount();i++){
				var rec =ds.getAt(i);
				if(rec.get('id')==file.id){
					rec.set('state', file.filestatus);
					rec.set('url',data.url);
					rec.commit();
				}
			}			
		}else{
			for(var i=0;i<ds.getCount();i++){
				var rec =ds.getAt(i);
				if(rec.get('id')==file.id){
					rec.set('percent', 0);
					rec.set('state', -3);
					rec.commit();
				}
			}
			MsgTip.msg({
			     msg:data.message
			     ,cmp:me
			     ,pos:'center'
			});
		}
		me.linkBtnEvent();
	},
	uploadProgress : function(file, bytesComplete, totalBytes){//处理进度条
		var me = this.customSettings.scope_handler;
		var percent = Math.ceil((bytesComplete / totalBytes) * 100);
		percent = percent == 100? 99 : percent;
       	var ds = me.gp.store;
		for(var i=0;i<ds.getCount();i++){
			var record =ds.getAt(i);
			if(record.get('id')==file.id){
				record.set('percent', percent);
				record.set('state', file.filestatus);
				record.commit();
			}
		}
	},
	onUploadError : function(file, errorCode, message) {
		var me = this.customSettings.scope_handler;
		me.linkBtnEvent();
		var ds = me.gp.store;
		for(var i=0;i<ds.getCount();i++){
			var rec =ds.getAt(i);
			if(rec.get('id')==file.id){
				rec.set('percent', 0);
				rec.set('state', file.filestatus);
				rec.commit();
			}
		}
	},
	onFileError : function(file,n){
		var stats =this.getStats();
		var me =this.customSettings.scope_handler;
		switch(n){
			case -100 :
			   var fileCout =this.settings.file_upload_limit;
			   tip('待上传文件列表数量超限，不能选择！只能上传'+fileCout+'个文件！');
			   break;
			case -110 : 
			   var fileSize=this.settings.file_size_limit;
			   tip('文件太大，不能选择！文件限制为'+fileSize);
			break;
			case -120 : tip('该文件大小为0，不能选择！');
			break;
			case -130 : 
			   var fileType=this.settings.file_types_description||this.settings.file_types;
			   tip('该文件类型不可以上传！只能上传以下文件类型:'+fileType);
			break;
		}
		function tip(msg){
				MsgTip.msg({
			     msg:msg
			     ,cmp:me
			     ,pos:'center'
				});
		}
	},
	onDiaogComplete : function(){
		var me = this.customSettings.scope_handler;
		me.linkBtnEvent();
	},
	stopUpload : function() {
		if (this.swfupload) {
			this.swfupload.uploadStopped = true;
			this.swfupload.stopUpload();
		}
	},
	deleteAll : function(){
		var ds = this.gp.store;
		for(var i=0;i<ds.getCount();i++){
			var record =ds.getAt(i);
			var file_id = record.get('id');
			this.swfupload.cancelUpload(file_id,false);			
		}
		//ds.removeAll();
		this.onDeleteAll();
		this.swfupload.uploadStopped = false;
	},
	onDeleteAll:function(show){
		var me =this;
		var ds = this.gp.store;
		if(show===false){
			for(var i=0;i<ds.getCount();i++){
			       		var rec =ds.getAt(i);
			       		me.onDeleteRec(rec,true);
			       }
			 MsgTip.msg({
						 	msg:"删除成功",
						 	cmp:me,
						 	pos:"center"
						  });   
			
			}	
			else {
			   Ext.Msg.confirm('确定','是否移取所有文件?如果有文件已经上传，那么该文件将会被删除！',function(n){
			       if (n=="yes" ) {
			       	for(var i=0;i<ds.getCount();i++){
			       		var rec =ds.getAt(i);
			       		me.onDeleteRec(rec,true);
			      	 }
			      	 MsgTip.msg({
						 	msg:"删除成功",
						 	cmp:me,
						 	pos:"center"
						  });
			       }
			});
		}
	},
	onDeleteRec:function(rec,all) {
		var me  =this;
		var ds = this.gp.store;
		if (rec!=null) {
			if (rec.get('state')== -4) {
					//要先做移取操作 增加一个判断对文件上传成功的是否做删除操作
					if (this.removeUpload&&this.deleteUrl&&rec.get('url')){
						var deletePath =this.deletePath;
						var url =this.deleteUrl;
						var param={};
						param[deletePath] =rec.get('url');
						var def =function(n){
						       if (n=='yes') {
						       	 Ext.Ajax.request({
						       	    url:url
						       	    ,method:'post'
						       	    ,params:param
						       	    ,success:function(result,request) {
						       	    	 if (!all) {
						       	    	  MsgTip.msg({
										 	msg:"移除成功",
										 	cmp:me,
										 	pos:"center"
						  				  });
						       	    	 }
						       	    	 ds.remove(rec);
						       	    }
						       	 });
						       	 
						       }
						};
						if (all) {
							def('yes');
						} else {
							Ext.Msg.confirm('确定','文件已经上传成功，确定要移取该文件?',def);
						}
					} else {
						ds.remove(rec);
					}
				} else {
					ds.remove(rec);
				}
		}
	},
	formatDelBtn : function(v){
		return "<a href='#' id='"+v+"'  style='color:blue' class='link-btn' ext:qtip='移除该文件'>移除</a>";
	},
	linkBtnEvent : function(){
		Ext.select('a.link-btn',false,this.gp.el.dom).on('click',function(o,e){
			var me =this;
			var ds = this.gp.store;
			for(var i=0;i<ds.getCount();i++){
				var rec =ds.getAt(i);
				if(rec.get('id')==e.id){
					this.onDeleteRec(rec);
				}
			}			
			this.swfupload.cancelUpload(e.id,false);
			//alert(this.swfupload.getStats().successful_uploads);
		},this);
	}
});
Ext.reg('uploadPanel',keel.UploadPanel);

/*
Ext.onReady(function(){
Ext.QuickTips.init();
new Ext.Panel({
			applyTo:'test'
			,buttons:[{text:'上传'
						,handler:function(){
							new Ext.Window({
								width : 650,
								title : '挽回例子',
								height : 300,
								layout : 'fit',
								buttonAlign:'center',
								items : [
									{
										xtype:'uploadPanel',
										border : false,
										deleteUrl:'upload_deleteFile.action',
										fileSize : '500 MB',//限制文件大小
										uploadUrl : 'upload_swfLoad.action',
										flashUrl : 'js/mycom/uploader/swfupload.swf',
										filePostName : 'file', //后台接收参数
										fileTypes : '*.xls;*.xlsx',//可上传文件类型
										file_types_description:'excel表格文件(*.xls;*.xlsx)',
										postParams : {dir:'retrive',taskId:"103001001004"} ,//上传文件存放目录
										fileCount:1
									}
									
								]
							   ,buttons:[{text:'确定',handler:function(){
							  		 	var panel =this.ownerCt.ownerCt.getComponent(0);
							  		 	var count =0;
							  		 	var param={};
							  		 	param.fileNames="";
							  		 	param.filePaths="";
							  		 	param.taskId="103001001004";
							  		 	param.mainProcessId=1;
							  		 	param.subProcessId=1;
							  		 	param.activityInsId=1;
							  		 	param.taskSeqNo=1;
									for(var i=0;i<panel.gp.getStore().getCount();i++){
										var rec =panel.gp.getStore().getAt(i);
										if(rec.get('state')==-4){
										    count++;
										    param.fileNames+=":"+rec.get('name');
										    param.filePaths+=":"+rec.get('url');
										}
									}
									if (count==0) {
										MsgTip.msg({
										 	msg:"没有上传成功的文件！",
										 	pos:"center"
									  		});
										return;
									}
									param.fileNames=param.fileNames.substring(1);
									param.filePaths=param.filePaths.substring(1);
									
									//请求
									var myMask = new Ext.LoadMask(this.ownerCt.ownerCt.getEl(), {msg:"请稍等，正保存导入文件日志中。。。"});
									myMask.show();
									Ext.Ajax.request({
										url:'retrive_addLog.action'
										,params:param
										,method:'post'
										,success:function(result,requst) {
											var page =Ext.decode(result.responseText);
												myMask.hide();
											if (page.status ==200){
												panel.ownerCt.close();
												delete param.fileNames;
												delete param.filePaths;
												Ext.Ajax.request({
													url:'retrive_startDealExcel.action'
													,params:param
													,method:'post'
													,success:function(result,requst) {
														MsgTip.msg({
													 	msg:"线程启动成功!",
													 	pos:"center"
												  		});
													}
												});
											}
										}
										,failure:function(){
											myMask.hide();
										}
									})
							   }}
							          ,{text:'关闭'
							            ,handler:function(){
							            	var panel =this.ownerCt.ownerCt.getComponent(0);
								   		 	var count =0;
											for(var i=0;i<panel.gp.getStore().getCount();i++){
												var rec =panel.gp.getStore().getAt(i);
												if(rec.get('state')==-4){
												    count++;
												}
											}
											if (count>0) {
												Ext.Msg.confirm('警告','有'+count+"文件已经成功上传确定要关闭？关闭后，上传文件将删除?",function(n){
												           if (n =='yes') {
												           	   //删除文件ajax
												           	   //请求
															   var myMask = new Ext.LoadMask(panel.ownerCt.getEl(), {msg:"请稍等，正在删除文件中。。。"});
															   myMask.show();
															   var exp =false;
												           	   try {
												           	   		panel.onDeleteAll(false);
												           	   } catch (err){
												           	   	    exp =true;  
												           	   	     MsgTip.msg({
																	 	msg:"移除失败！",
																	 	cmp:panel.ownerCt,
																	 	pos:"center"
												  				  });
												           	   }
												           	   if (!exp) {
													           	   myMask.hide();
													           	   panel.ownerCt.close();
												           	   }
												           }
												});
											} else {
							            		panel.ownerCt.close();
											}
							            }}]
							}).show();
						}}
					 ,{text:'查看已经上传',handler:function(){
					 		new Ext.Window({
								width : 1000,
								title : '已上传文件',
								height : 300,
								params:{
					        	        taskId:'103001001004'
					        	        ,mainProcessId:'1'
					        	        ,subProcessId:'1'
					        	        ,activityInsId:'1'
								       },
								layout : 'fit',
								buttonAlign:'center',
								items : [{
								    xtype:'grid'
								    ,loadMask:{msg:'请稍候，正在加载中。。。'}
								    ,tbar:[{text:'刷新'
								    		,handler:function(){
								    		    var grid =this.ownerCt.ownerCt;
								    		    grid.getStore().load({
								        	     	params:grid.ownerCt.params
								        	});
								    		
								    		}},'-']
								    ,store:{
								       xtype:'jsonstore'
								       ,fields:['seqNo','operator','operTime','fileName','mainProcessId','subProcessId','activityPnsId','taskSeqNo','taskId','operateFlag','filePath','resultInfo']
								       ,url:'retrive_getRetriveLog.action'
								       ,root:'root'
								    }
								    ,viewConfig:{
								    }
								    ,columnLines:true
								    ,listeners:{
								        'afterrender':function(){
								        	this.getStore().load({
								        	     params:this.ownerCt.params
								        	});
								        }
								    }
								    ,columns:[
								    	{header:'文件名',dataIndex:'fileName',width:200}
								    	,{header:'操作时间',dataIndex:'operTime',width:200}
								    	,{header:'处理状态',dataIndex:'operateFlag',width:100,renderer:function(value){
								    	              var retv =value;
								    	              if (value =="0") {
								    	              	retv="导入";
								    	              } else if (value =="1") {
								    	              	retv ="解析中";
								    	              }else if (value=='2') {
								    	              	retv ="处理成功"
								    	              } else if (value =="3"){
								    	              	retv ='处理失败';
								    	              }
								    	              return retv;
								    	}}
								    	,{header:'处理结果',width:50,dataIndex:'resultInfo',width:300,cellTip:true}
								    	,{header:'操作',width:150,dataIndex:'seqNo'
								    		,renderer:function(value){
								    				return "<a href='#' id='"+value+"'  style='color:blue;margin:0 0 0 10;' class='delete-file' ext:qtip='删除导入记录并删除文件'>删除</a>"+
								    					"<a href='#' id='"+value+"'  style='color:blue;margin:0 20 0 10;' class='update-file' ext:qtip='重新处理该条记录'>重新处理</a>"
								    		},processEvent:function(name, e, grid, rowIndex, colIndex){
								    	        if(name =="click") {
								    	        	var m = e.getTarget().className;
								    	        	var id =e.getTarget().id;
								    	        	if (m =='delete-file') {
								    	        		var myMask = new Ext.LoadMask(grid.el, {msg:"请稍等,正在删除中..."});
								    	        		Ext.Msg.confirm('确认','确认要删除记录？',function(n){
								    	        		         if (n=='yes') {
								    	        		         	myMask.show();
								    	        		         	Ext.Ajax.request({
								    	        		         	    loadTask:myMask
								    	        		         	    ,url:'retrive_deleteLog.action'
								    	        		         	    ,params:{seq_no:id}
								    	        		         	    ,success:function(result,request) {
								    	        		         	    	var page =Ext.decode(result.responseText);
								    	        		         	    	myMask.hide();
								    	        		         	    	if (page.status==200) {
								    	        		         	    		MsgTip.msg({msg:'删除记录成功',cmp:grid,pos:'center'});
								    	        		         	    		grid.store.load({
																	        	     params:grid.ownerCt.params
																	        	});
								    	        		         	    	}
								    	        		         	    	
								    	        		         	    }
								    	        		         	    ,failure:function(result,request) {
								    	        		         	    	myMask.hide();
								    	        		         	    }
								    	        		         	});
								    	        		         	
								    	        		         } 
								    	        		});
								    	        		
								    	        	} else if(m=='update-file') {
								    	        		var myMask = new Ext.LoadMask(grid.el, {msg:"请稍等,正在开启重新处理线程中..."});
								    	        		Ext.Msg.confirm('确认','确认要重新处理记录？',function(n){
								    	        		         if (n=='yes') {
								    	        		         	myMask.show();
								    	        		         	Ext.Ajax.request({
								    	        		         	    loadTask:myMask
								    	        		         	    ,url:'retrive_reDealExcel.action'
								    	        		         	    ,params:{seq_no:id}
								    	        		         	    ,success:function(result,request) {
								    	        		         	    	var page =Ext.decode(result.responseText);
								    	        		         	    	myMask.hide();
								    	        		         	    	if (page.status==200) {
								    	        		         	    		MsgTip.msg({msg:'重新处理开始',cmp:grid,pos:'center'});
								    	        		         	    		grid.store.load({
																	        	     params:grid.ownerCt.params
																	        	});
								    	        		         	    	}
								    	        		         	    	
								    	        		         	    }
								    	        		         	    ,failure:function(result,request) {
								    	        		         	    	myMask.hide();
								    	        		         	    }
								    	        		         	});
								    	        		         	
								    	        		         } 
								    	        		});
								    	        	}
								    	        	return this.fireEvent(name, this, grid, rowIndex, e);
								    	        } else if(name == 'mousedown'){
								    	        	return false;
								    	        }
								    	        
								    		}
								    	}
								    ]
								}]
					 	}).show()
					 	}}]
			});
});
*/